<template>
  <div class="app-container">
    <el-form ref="form" inline>
      <el-form-item>
        <el-input
          v-model="input"
          placeholder="用户名"
          style="width: 200px"
        ></el-input>
      </el-form-item>
      <el-button type="primary"  @click="search">查询</el-button>
      <el-button>取消</el-button>
    </el-form>
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button type="danger" @click="lotRemove">批量删除</el-button>
    <!-- 表格区域 -->
    <el-table
      ref="singleTable"
      :data="userList.items"
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%; margin-top: 20px"
      border
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="center">
      </el-table-column>
      <el-table-column property="username" label="用户名"> </el-table-column>
      <el-table-column property="nickName" label="用户昵称"> </el-table-column>
      <el-table-column property="roleName" label="权限列表"> </el-table-column>
      <el-table-column property="gmtCreate" label="创建时间"> </el-table-column>
      <el-table-column property="gmtModified" label="更新时间">
      </el-table-column>
      <el-table-column property="address" label="操作">
        <template slot-scope="{ row }">
          <el-button
            type="info"
            icon="el-icon-user-solid"
            size="mini"
            @click="giveRole(row)"
          ></el-button>
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="addUser(row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delet(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器区域 -->
    <el-pagination
      style="margin-top: 20px"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :page-size="limit"
      layout="prev, pager, next, jumper"
      :total="20"
    >
    </el-pagination>

    <!-- 添加弹窗 -->
    <el-dialog
      :title="user.id ? '修改用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
      class="demo-ruleForm"
    >
      <el-form :model="user" :rules="rules" ref="user">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" label-width="120px">
          <el-input v-model="user.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          v-if="!user.id"
          label-width="120px"
          prop="password"
        >
          <el-input v-model="user.password" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('user')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="角色分配" :visible.sync="dialogFormVisible2">
      <el-form :model="form" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="角色管理">
          <el-checkbox
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="checkedRoles"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox v-for="role in roles" :label="role" :key="role">{{
              role
            }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="doAssign()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      selectedIds:[],
      input: "",
      currentPage: 1,
      limit: 4,
      userList: [],
      form: {},
      user: {},
      dialogFormVisible: false,
      dialogFormVisible2: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 4, message: "不能小于四位" },
        ],
        password: [{ required: true, validator: this.validator }],
      },
      checkAll: false,
      checkedRoles: [],
      isIndeterminate: true,
      roles: [],
      allRolesList:[],
      assignRoles:[],
      assignRoleId:[],
      userId:''
    };
  },
  methods: {
   async doAssign(){
      this.assignRoleId = this.allRolesList.filter(item=>this.checkedRoles.includes(item.roleName))
      let roleId = this.assignRoleId.map(item=>item.id)
      let newId = roleId.reduce((pre,item)=>{
        return pre +','+item
      })
     await this.$api.user.doAssign(this.userId,newId)
      this.getUser(this.currentPage)
      this.dialogFormVisible2 = false
    },
    handleCheckAllChange(val) {
      this.checkedRoles = val ? this.roles : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roles.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.roles.length;
    },
     handleSelectionChange(selection) {
       console.log('------',selection)
      this.selectedIds = selection.map((item) => item.id)
    },


    // 批量删除
   async lotRemove(){
      let  res = await this.$api.user.batchRemove(this.selectedIds)
      if(res.code===20000){
        this.$message('删除成功')
      }
      this.getUser()
    },
    handleCurrentChange(val) {
      this.currentPage2 = val;
      this.getUser(this.currentPage);
    },
    async getUser(page = 1,keyword) {
      console.log(111111,keyword)
      let result = await this.$api.user.getCategoryUser(page, this.limit,keyword);
      console.log(result);
      if (result.code == 20000) {
        this.userList = result.data
      }
    },
    addUser(row) {
      this.dialogFormVisible = true;
      if (row.id) {
        this.user = row;
      }
    },
    
    async giveRole(row) {
      this.userId = row.id
      console.log(row.roleName)
      this.checkedRoles = row.roleName.split(',')
      this.dialogFormVisible2 = true;
      let result = await this.$api.user.toAssign(row.id);
      if (result.code == 20000) {
        this.roles = result.data.allRolesList.map(item=>item.roleName)
        this.allRolesList  =result.data.allRolesList
        this.assignRoles =result.data.assignRoles
      }
    },
    submitForm(user) {
      this.$refs[user].validate(async (valid) => {
        if (valid) {
          if (this.user.id) {
            await this.$api.user.upp(this.user);
          } else {
            await this.$api.user.add(this.user);
          }
          this.getUser(user.id ? this.currentPage : 1);
          this.user = {};
          this.$message("保存成功");
          this.dialogFormVisible = false;
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    validator(rules, value, callback) {
      if (!value) {
        callback("密码必须输入");
      } else if (!value || value.length < 6) {
        callback("密码不能小于6位");
      } else {
        callback();
      }
    },

    search(){
    this.getUser(1,this.input)
    this.currentPage = 1
  },
    async delet(id){
      await this.$api.user.removeUser(id)
   }
  },

  
  mounted() {
    this.getUser();
  },
  
};
</script>

<style scoped>
</style>